const { publish } = require("../websocket/monitorWsServer.js");

// 采集并广播接口调用信息
function monitorMiddleware(req, res, next) {
  const startAt = Date.now();

  const requestInfo = {
    id: `${startAt}-${Math.random().toString(36).slice(2, 8)}`,
    url: req.originalUrl,
    method: req.method,
    query: req.query,
    params: req.params,
    ip: req.ip,
    headers: pickHeaders(req.headers),
    body: safeBody(req.body),
    time: new Date(startAt).toISOString(),
    event: "request",
  };

  // 广播请求事件
  try {
    publish(requestInfo);
  } catch {}

  // 捕获响应
  const originalJson = res.json.bind(res);
  const originalSend = res.send.bind(res);
  let responseBody;

  res.json = (body) => {
    responseBody = body;
    return originalJson(body);
  };

  res.send = (body) => {
    responseBody = body;
    return originalSend(body);
  };

  res.on("finish", () => {
    const durationMs = Date.now() - startAt;
    const responseInfo = {
      id: requestInfo.id,
      url: req.originalUrl,
      method: req.method,
      status: res.statusCode,
      durationMs,
      response: safeBody(responseBody),
      time: new Date().toISOString(),
      event: "response",
    };
    try {
      publish(responseInfo);
    } catch {}
  });

  next();
}

function safeBody(body) {
  try {
    if (Buffer.isBuffer(body)) return `Buffer(${body.length})`;
    return body;
  } catch {
    return undefined;
  }
}

function pickHeaders(headers) {
  const allow = [
    "content-type",
    "user-agent",
    "referer",
    "x-forwarded-for",
  ];
  const picked = {};
  for (const key of allow) {
    if (headers[key] !== undefined) picked[key] = headers[key];
  }
  return picked;
}

module.exports = monitorMiddleware;


